package com.xiaoma.springbootannotation.demo;

import com.xiaoma.springbootannotation.demo.entity.Request;
import com.xiaoma.springbootannotation.demo.entity.Response;
import com.xiaoma.springbootannotation.demo.handler.AbstractHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @Author: xiaoma
 * @Date: 2021/12/22 16:23
 */
@Component
public class HandlerChain extends AbstractHandler implements BeanPostProcessor{

    private final List<AbstractHandler> list = new ArrayList<>();

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof AbstractHandler){
            list.add((AbstractHandler) bean);
        }
        return null;
    }

    @Override
    public Response doFilter(Request request, Response response) {
        for (AbstractHandler handler : list) {
            Response res = handler.doFilter(request, response);
            if (res.isFlag()) break;
        }
        return response;
    }
}
